/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package groupe;

import java.awt.Event;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.swing.filechooser.FileFilter;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author Ter Murga Victor
 */
public class Utility {

    public static JFileChooser ouvrirOpenBox(String url, JFrame frame){
        JFileChooser chooser;
        if (url!=null){
            chooser = new JFileChooser(url);
        } else {
            chooser = new JFileChooser();
        }
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.addChoosableFileFilter(new FileFilter() {
            public boolean accept(File pathname) {
                if (pathname.isDirectory()) {
                    return true;
                }
                String extension = getExtension(pathname);
                if (extension != null) {
                    if (extension.equals("xml") ) {
                            return true;
                    } else {
                        return false;
                    }
                }
                return false;
            }

            @Override
            public String getDescription() {
                return "Profil Eprofilea (.xml)";
            }
        });
        int returnVal = chooser.showOpenDialog(frame);
        if(returnVal == JFileChooser.APPROVE_OPTION){
            return chooser;
        } else {
            return null;
        }
    }

        public static JFileChooser ouvrirOpenBox2(String url, JFrame frame){
        JFileChooser chooser;
        if (url!=null){
            chooser = new JFileChooser(url);
        } else {
            chooser = new JFileChooser();
        }
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.addChoosableFileFilter(new FileFilter() {
            public boolean accept(File pathname) {
                if (pathname.isDirectory()) {
                    return true;
                }
                String extension = getExtension(pathname);
                if (extension != null) {
                    if (extension.equals("str") ) {
                            return true;
                    } else {
                        return false;
                    }
                }
                return false;
            }

            @Override
            public String getDescription() {
                return "Structure Eprofilea (.str)";
            }
        });
        int returnVal = chooser.showOpenDialog(frame);
        if(returnVal == JFileChooser.APPROVE_OPTION){
            return chooser;
        } else {
            return null;
        }
    }

    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }

    public static void addMenuItem(ActionListener frame, JMenu m, String label, String command, int key) {
        JMenuItem menuItem;
	menuItem = new JMenuItem(label);
        m.add(menuItem);

        menuItem.setActionCommand(command);
        menuItem.addActionListener(frame);
	if (key > 0) {
            if (key != KeyEvent.VK_DELETE)
		menuItem.setAccelerator(KeyStroke.getKeyStroke(key, Event.CTRL_MASK, false));
            else
		menuItem.setAccelerator(KeyStroke.getKeyStroke(key, 0, false));
	}
    }

    public static void addButton(ActionListener frame, JComponent p, String name, String tooltiptext, String actionCommand, String imageName) {
	  JButton b;
	  if ((imageName == null) || (imageName.equals(""))) {
              b = (JButton) p.add(new JButton(name));
	  } else {
              java.net.URL u = frame.getClass().getResource(imageName);
              if (u != null){
                  ImageIcon im = new ImageIcon (u);
                  b = (JButton) p.add(new JButton(im));
              } else
                  b = (JButton) p.add(new JButton(name));

	  }
          b.setActionCommand(actionCommand);
	  b.setToolTipText(tooltiptext);
	  //b.setBorder(BorderFactory.createRaisedBevelBorder());
	  //b.setMargin(new Insets(0,0,0,0));
	  b.addActionListener(frame);
    }

    public static void exit(){
        System.exit(0);
    }

    public static Element getElement(String url) throws ParserConfigurationException, SAXException, IOException{
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = db.parse(url);
        System.out.println(url);
        return doc.getDocumentElement();
    }

    public static String getPath(Object o, String cheminDestinataire) throws UnsupportedEncodingException{
        String nomProjet = "Eprofilea_TER_2009";
        String path = "/" + GroupeApp.class.getName().replace('.', '/') + ".class";
        URL url = o.getClass().getResource(path);
        path = URLDecoder.decode(url.toString(), "UTF-8");
        //System.out.println("Répertoire contenant la classe: " + path);
        // suppression de  la classe ou du jar du path de l'url
        int index = path.lastIndexOf("/");
        path = path.substring(0, index);
        //System.out.println("Répertoire contenant la classe: " + path);
        if (path.startsWith("jar:file:")) {
            // suppression de jar:file: de l'url d'un jar
            // ainsi que du path de la classe dans le jar
            index = path.indexOf("!");
            path = path.substring(9, index);
            //System.out.println("dans if Répertoire contenant la classe: " + path);
        } else {
            // suppresion du file: de l'url si c'est une classe en dehors d'un jar
            // et suppression du path du package si il est présent.
            path = path.substring(5, path.length());
            //System.out.println("dans else Répertoire contenant la classe: " + path);
            Package pack = o.getClass().getPackage();
            if (null != pack) {
                String packPath = pack.toString().replace('.', '/');
                if (path.endsWith(packPath)) {
                    path = path.substring(0, (path.length() - packPath.length()));
                }
            }
            //.out.println("dans else Répertoire contenant la classe: " + path);
        }
        path = path.substring(0, path.indexOf(nomProjet)+nomProjet.length());
        if (cheminDestinataire!=null){
            path+=cheminDestinataire;
        }
        //System.out.println("Répertoire contenant la classe: " + path);
        return path;
    }


      public static void crear(String url, String destin) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException{
       try {
			// Lectura de fichero_origen.xml
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document documento = builder.parse(url);

			// Ahora documento es el XML leido en memoria.

			// Escritura de fichero_destino.xml
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(documento);
			StreamResult result = new StreamResult(destin);
			transformer.transform(source, result);
		}
       catch (Exception e) {
			e.printStackTrace();
		}
      
    }
    

   /* public static String getCommentaire(Node node){
        //String result = null;
        if(node.getAttributes().getNamedItem("commentaire")!=null){
            String commentaire = node.getAttributes().getNamedItem("commentaire").toString();
            commentaire = commentaire.substring(commentaire.indexOf("\"")+1, commentaire.lastIndexOf("\""));
            if(!commentaire.equals("") && !commentaire.equals(" ")){
                return commentaire;
            }
        }
        return null;
    }*/
}
